#! /bin/bash
#
# set lfs enviroments.
#
# !! This script is designed for modifying enviroment, so
#    running this directly is useless. Please exec `. env.env'
#

self=env.env

# usage: env_out [WARN|ERR|INFO]
env_out()
{
	local type=INFO fd=1

	case "$1" in
		INFO|WARN|ERR)
			type=$1; shift
			;;
	esac

	[ "$type" = "info" ] || fd=2

	echo "[$type] <$self>: $@" >& $fd
}

env_info() { env_out INFO "$@"; }
env_err()  { env_out ERR  "$@"; exit 1; }
env_warn() { env_out WARN "$@"; }

[ "$(basename -- "$0")" = "$self" ] && \
	env_warn "Run the script directly is useless !!"

[ -e "$self" ] || env_err "import env out lfs directory is invalid !!"

LFS_ROOT="$PWD"
LFS_ARCH=$(uname -m)
LFS_CPUNUM=$(cat /proc/cpuinfo | grep "^processor" | wc -l)
LFS_TARGET=$LFS_ARCH-nwolf-linux-gnu
LFS_TARGET_LAST=$LFS_ARCH-linux-gnu
LFS_MAKEFLAGS="-j$LFS_CPUNUM"

LFS_SOURCES="$LFS_ROOT/sources"
LFS_TMP="$LFS_ROOT/tmp/$LFS_ARCH/haywire"
LFS_TESTS="$LFS_ROOT/test"

LFS_MNT=$LFS_ROOT/mnt/$LFS_ARCH
LFS_TOOLS="$LFS_MNT/tools"

LFS_UID=$UID

for x in \
	"$LFS_SOURCES" "$LFS_MNT" "$LFS_TMP" "$LFS_TESTS"; do
	mkdir -p "$x" || env_err "create directory $x fail."
done

[ "$(readlink /tools 2>/dev/null)" != "$LFS_TOOLS" ] && {
	sudo ln -svf "$LFS_TOOLS" / || env_err "ln $LFS_TOOLS fail"
}
[ "$(readlink /lfs-mnt 2>/dev/null)" != "$LFS_MNT" ] && {
	sudo ln -svf "$LFS_MNT" /lfs-mnt || env_err "ln $LFS_MNT fail"
}

set +h
umask 022
LC_ALL=POSIX

# reset LFS_TOOLS
LFS_TOOLS=/tools

[ -n "$(grep "$LFS_ROOT/bin" <<<$PATH)" ] || PATH=$PATH:$LFS_ROOT/bin
[ -n "$(grep "^$LFS_TOOLS/bin" <<<$PATH)" ] || PATH=$LFS_TOOLS/bin:$PATH

vars="LFS_ROOT LFS_ARCH LFS_CPUNUM LFS_TARGET LFS_TARGET_LAST
      LFS_SOURCES LFS_MAKEFLAGS LFS_TOOLS LFS_TMP LFS_TESTS LFS_MNT
      LFS_UID
      PATH"

env_result()
{
	export $vars

	echo "---------------------------------"
	echo "LFS env variable info"
	for x in $vars; do

		printf "\t%-13s = '%s'\n" $x $(eval echo \$$x)
	done
	echo "---------------------------------"
}

env_result
env_info "lfs env init ok"
